hdu 5545 Battle of Guandu

  题目比较麻烦,直接说想法。一个村庄对应曹操的战场和袁绍的战场,可以转化为一个从曹操的战场到袁绍的战场的边,边的权值为雇佣费用。

  重要度为2的点的人至少要多1个人,而每个重要度为2的点多1个人就会导致它指向的点也多一个人,如果这个点重要度为1或2,那么这个人就还要转移出去,如果重要度是0就不用继续转移了。所以这道题的做法就是最短路,每个村庄对应的曹操战场指向袁绍战场为一条有向边,每个重要度为2的点到距离它最近的0重要度的点的最短路长度的和。这个是一个多源最短路,是会TLT的,但是所有重要度为0的点可以捏成一个点,因为它们都是最短路的终点,所以转换为多个点到一个点的最短路。然后可以把边反向,转换成一个点到其他所有点的单源最短路的长度的和。所以其实就是一个单元最短路,但是感觉还是不太好看出来的。

  Github: https://github.com/wmpeng/Algorithm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
#define INF 2100000000000000000ll
using namespace std;
int n, m, x[100005], y[100005], c[100005], w[100005];
bool vis[100005];
long long dis[100005];

typedef pair<int, int> edge;
typedef pair<int, long long> node;
vector<edge> adjList[100005];
bool operator<(node n1, node n2)
{
return n1.second < n2.second;
}
void peng()
{
int i, j;
priority_queue<node> q;
for (i = 0; i <= 100004; i++)
{
adjList[i].clear();
dis[i] = INF;
vis[i] = false;
}
for (i = 1; i <= n; i++)
{
if (w[y[i]] == 0)
adjList[0].push_back(edge(x[i], c[i]));//把所有为0的点归到一起
else if (w[x[i]] == 0)
adjList[y[i]].push_back(edge(0, c[i]));
else
adjList[y[i]].push_back(edge(x[i], c[i]));
}

q.push(node(0 ,0));
dis[0] = 0;
while (!q.empty())
{
int curr = (q.top()).first;
q.pop();
vis[curr] = true;
for (vector<edge>::iterator it = adjList[curr].begin(); it != adjList[curr].end(); it++)
if (dis[curr] + it->second < dis[it->first])
{
dis[it->first] = dis[curr] + it->second;
q.push({ it->first,dis[it->first] });

}
}

long long ans = 0;
for (i = 1; i <= m; i++)
if (w[i] == 2)
{
if (vis[i] == false)
{
cout << -1 << endl;
return;
}
else
ans += dis[i];
}
cout << ans << endl;
}

int main()
{
int i, j, t;
scanf("%d", &t);
for (i = 1; i <= t; i++)
{
scanf("%d%d", &n, &m);
for (j = 1; j <= n; j++)
scanf("%d", &x[j]);
for (j = 1; j <= n; j++)
scanf("%d", &y[j]);
for (j = 1; j <= n; j++)
scanf("%d", &c[j]);
for (j = 1; j <= m; j++)
scanf("%d", &w[j]);
printf("Case #%d: ", i);
peng();

}
}